/*
 * @lc app=leetcode.cn id=25 lang=javascript
 *
 * [25] K 个一组翻转链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
var reverseKGroup = function(head, k) {
    if (!head || k < 2) return head;
    let ret = new ListNode(-1,head);
    let cur = ret

    while(cur){
        let temp = reverse(cur.next,k)
        cur.next = temp

        let con = k
        while(con-- && cur){
            cur = cur.next
        }
    }

    return ret.next
};

function reverse(head,n){
    if (!head || !head.next) return head;
    // 判断是否满足k个节点
    let con = n;
    let cur = head
    while(cur && --con){
        cur = cur.next
    }
    if(!cur)return head

    let p = null
    cur = head
    while(cur && n--){
        let temp = cur.next
        cur.next = p
        p = cur
        cur = temp
    }
    head.next = cur
    return p

    
}

// @lc code=end

